<template>
  <div class="dict-management">
    <n-grid :cols="2" :x-gap="12">
      <!-- Left Side - Dictionary Types -->
      <n-grid-item>
        <n-card title="字典类型">
          <template #header-extra>
            <n-space>
              <n-button type="primary" @click="handleAddType">
                新增
              </n-button>
            </n-space>
          </template>

          <!-- Search Form -->
          <n-space vertical>
            <n-form inline :model="typeSearchForm">
              <n-form-item label="类型">
                <n-select
                  v-model:value="typeSearchForm.status"
                  :options="[
                    { label: '启用', value: 1 },
                    { label: '禁用', value: 0 }
                  ]"
                  placeholder="请选择状态"
                  clearable
                />
              </n-form-item>
              <n-form-item>
                <n-input
                  v-model:value="typeSearchForm.keyword"
                  placeholder="关键词搜索名称、KEY"
                />
              </n-form-item>
              <n-form-item>
                <n-button type="primary" @click="handleTypeSearch">
                  查询
                </n-button>
                <n-button class="ml-2" @click="handleTypeReset">
                  重置
                </n-button>
              </n-form-item>
            </n-form>

            <!-- Dictionary Types Table -->
            <n-data-table
              :columns="typeColumns"
              :data="typeData"
              :pagination="typePagination"
              @update:page="handleTypePageChange"
              @update:selected-keys="handleTypeSelect"
            />
          </n-space>
        </n-card>
      </n-grid-item>

      <!-- Right Side - Dictionary Items -->
      <n-grid-item>
        <n-card :title="selectedType ? `字典项 - ${selectedType.name}` : '字典项'">
          <template #header-extra>
            <n-space>
              <n-button
                type="primary"
                @click="handleAddItem"
                :disabled="!selectedType"
              >
                新增
              </n-button>
            </n-space>
          </template>

          <!-- Search Form -->
          <n-space vertical>
            <n-form inline :model="itemSearchForm">
              <n-form-item label="状态">
                <n-select
                  v-model:value="itemSearchForm.status"
                  :options="[
                    { label: '启用', value: 1 },
                    { label: '禁用', value: 0 }
                  ]"
                  placeholder="请选择状态"
                  clearable
                />
              </n-form-item>
              <n-form-item>
                <n-input
                  v-model:value="itemSearchForm.keyword"
                  placeholder="关键词搜索名称、编号"
                />
              </n-form-item>
              <n-form-item>
                <n-button type="primary" @click="handleItemSearch">
                  查询
                </n-button>
                <n-button class="ml-2" @click="handleItemReset">
                  重置
                </n-button>
              </n-form-item>
            </n-form>

            <!-- Dictionary Items Table -->
            <n-data-table
              :columns="itemColumns"
              :data="itemData"
              :pagination="itemPagination"
              @update:page="handleItemPageChange"
            />
          </n-space>
        </n-card>
      </n-grid-item>
    </n-grid>

    <!-- Dictionary Type Modal -->
    <n-modal v-model:show="showTypeModal" :title="typeModalTitle">
      <n-card style="width: 600px">
        <n-form
          ref="typeFormRef"
          :model="typeFormData"
          :rules="typeRules"
          label-placement="left"
          label-width="100"
        >
          <n-form-item label="名称" path="name">
            <n-input v-model:value="typeFormData.name" placeholder="请输入名称" />
          </n-form-item>
          <n-form-item label="标识KEY" path="key">
            <n-input
              v-model:value="typeFormData.key"
              placeholder="请输入标识KEY"
            />
          </n-form-item>
          <n-form-item label="模式级别" path="level">
            <n-select
              v-model:value="typeFormData.level"
              :options="[
                { label: '一级', value: '一级' },
                { label: '多级', value: '多级' }
              ]"
              placeholder="请选择模式级别"
            />
          </n-form-item>
          <n-form-item label="状态" path="status">
            <n-switch v-model:value="typeFormData.status" />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showTypeModal = false">取消</n-button>
            <n-button type="primary" @click="handleTypeSubmit">确定</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>

    <!-- Dictionary Item Modal -->
    <n-modal v-model:show="showItemModal" :title="itemModalTitle">
      <n-card style="width: 600px">
        <n-form
          ref="itemFormRef"
          :model="itemFormData"
          :rules="itemRules"
          label-placement="left"
          label-width="100"
        >
          <n-form-item label="名称" path="name">
            <n-input v-model:value="itemFormData.name" placeholder="请输入名称" />
          </n-form-item>
          <n-form-item label="编号" path="sn">
            <n-input
              v-model:value="itemFormData.sn"
              placeholder="请输入编号"
            />
          </n-form-item>
          <n-form-item label="状态" path="status">
            <n-switch v-model:value="itemFormData.status" />
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showItemModal = false">取消</n-button>
            <n-button type="primary" @click="handleItemSubmit">确定</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h } from 'vue'
import { NButton, NSpace, useMessage, NSwitch } from 'naive-ui'

const message = useMessage()

// Dictionary Types
const typeSearchForm = ref({
  status: null,
  keyword: ''
})

const typeColumns = [
  { title: '序号', key: 'id' },
  { title: '名称', key: 'name' },
  { title: '标识KEY', key: 'key' },
  { title: '模式级别', key: 'level' },
  { 
    title: '是否启用',
    key: 'status',
    render(row) {
      return h(
        NSwitch,
        {
          value: row.status,
          onUpdateValue: (value) => handleTypeStatusChange(row, value)
        }
      )
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(NSpace, null, {
        default: () => [
          h(
            NButton,
            {
              size: 'small',
              onClick: () => handleEditType(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => handleDeleteType(row)
            },
            { default: () => '删除' }
          )
        ]
      })
    }
  }
]

const typeData = ref([
  { 
    id: 1,
    name: 'codeGen_查询条件Java类型',
    key: 'code_gen_condition_java_type',
    level: '一级',
    status: true
  },
  {
    id: 2,
    name: '扩展',
    key: 'extend_dic_demo',
    level: '一级',
    status: true
  }
])

const typePagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// Dictionary Items
const selectedType = ref(null)
const itemSearchForm = ref({
  status: null,
  keyword: ''
})

const itemColumns = [
  { title: '名称', key: 'name' },
  { title: '编号(SN)', key: 'sn' },
  {
    title: '是否启用',
    key: 'status',
    render(row) {
      return h(
        NSwitch,
        {
          value: row.status,
          onUpdateValue: (value) => handleItemStatusChange(row, value)
        }
      )
    }
  },
  {
    title: '操作',
    key: 'actions',
    render(row) {
      return h(NSpace, null, {
        default: () => [
          h(
            NButton,
            {
              size: 'small',
              onClick: () => handleEditItem(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => handleDeleteItem(row)
            },
            { default: () => '删除' }
          )
        ]
      })
    }
  }
]

const itemData = ref([])
const itemPagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// Modals and Forms
const showTypeModal = ref(false)
const typeModalTitle = ref('')
const typeFormRef = ref(null)
const typeFormData = ref({
  name: '',
  key: '',
  level: '',
  status: true
})

const typeRules = {
  name: { required: true, message: '请输入名称', trigger: 'blur' },
  key: { required: true, message: '请输入标识KEY', trigger: 'blur' },
  level: { required: true, message: '请选择模式级别', trigger: 'change' }
}

const showItemModal = ref(false)
const itemModalTitle = ref('')
const itemFormRef = ref(null)
const itemFormData = ref({
  name: '',
  sn: '',
  status: true
})

const itemRules = {
  name: { required: true, message: '请输入名称', trigger: 'blur' },
  sn: { required: true, message: '请输入编号', trigger: 'blur' }
}

// Type Methods
function handleTypeSearch() {
  message.success('搜索成功')
}

function handleTypeReset() {
  typeSearchForm.value = {
    status: null,
    keyword: ''
  }
}

function handleAddType() {
  typeModalTitle.value = '新增字典类型'
  typeFormData.value = {
    name: '',
    key: '',
    level: '',
    status: true
  }
  showTypeModal.value = true
}

function handleEditType(row) {
  typeModalTitle.value = '编辑字典类型'
  typeFormData.value = { ...row }
  showTypeModal.value = true
}

function handleDeleteType(row) {
  message.success('删除成功')
}

function handleTypeStatusChange(row, value) {
  row.status = value
  message.success('状态修改成功')
}

function handleTypeSubmit() {
  typeFormRef.value?.validate((errors) => {
    if (!errors) {
      message.success('保存成功')
      showTypeModal.value = false
    }
  })
}

function handleTypePageChange(page) {
  typePagination.value.page = page
}

function handleTypeSelect(keys) {
  if (keys.length > 0) {
    selectedType.value = typeData.value.find(item => item.id === keys[0])
    loadItems()
  } else {
    selectedType.value = null
    itemData.value = []
  }
}

// Item Methods
function loadItems() {
  if (selectedType.value) {
    // Mock data - replace with actual API call
    itemData.value = [
      { name: '示例项1', sn: 'ITEM001', status: true },
      { name: '示例项2', sn: 'ITEM002', status: false }
    ]
  }
}

function handleItemSearch() {
  message.success('搜索成功')
}

function handleItemReset() {
  itemSearchForm.value = {
    status: null,
    keyword: ''
  }
}

function handleAddItem() {
  if (!selectedType.value) {
    message.warning('请先选择字典类型')
    return
  }
  itemModalTitle.value = '新增字典项'
  itemFormData.value = {
    name: '',
    sn: '',
    status: true
  }
  showItemModal.value = true
}

function handleEditItem(row) {
  itemModalTitle.value = '编辑字典项'
  itemFormData.value = { ...row }
  showItemModal.value = true
}

function handleDeleteItem(row) {
  message.success('删除成功')
}

function handleItemStatusChange(row, value) {
  row.status = value
  message.success('状态修改成功')
}

function handleItemSubmit() {
  itemFormRef.value?.validate((errors) => {
    if (!errors) {
      message.success('保存成功')
      showItemModal.value = false
    }
  })
}

function handleItemPageChange(page) {
  itemPagination.value.page = page
}
</script>

<style scoped>
.dict-management {
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.n-grid {
  flex: 1;
  height: 100%;
}

.n-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.n-card :deep(.n-card__content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.n-space {
  flex: 1;
  display: flex !important;
  flex-direction: column;
  height: 100%;
}

.n-data-table {
  flex: 1;
}

.ml-2 {
  margin-left: 8px;
}
</style>
